package net.sourceforge.peers.gui;

import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Optional;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import net.sourceforge.peers.Account;
import net.sourceforge.peers.FileLogger;
import net.sourceforge.peers.Logger;
import net.sourceforge.peers.javaxsound.JavaxSoundManager;
import net.sourceforge.peers.media.AbstractSoundManager;
import net.sourceforge.peers.sip.Utils;


/**
 * @author Mr.Yan
 */
public class MainFrame implements WindowListener, ActionListener {

    public static void main(final String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGUI(args));
    }

    private static void createAndShowGUI(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        new MainFrame(args);
    }

    private final JFrame mainFrame;
    private final JTextField uri;
    private final JLabel statusLabel;

    private EventManager eventManager;
    private final Registration registration;
    private final Logger logger;

    public MainFrame(final String[] args) {
        String peersHome = Utils.DEFAULT_PEERS_HOME;
        if (args.length > 0) {
            peersHome = args[0];
        }
        logger = new FileLogger(peersHome);
        String lookAndFeelClassName = UIManager.getSystemLookAndFeelClassName();
        try {
            UIManager.setLookAndFeel(lookAndFeelClassName);
        } catch (Exception e) {
            logger.error("cannot change look and feel", e);
        }
        final AbstractSoundManager soundManager = new JavaxSoundManager(false, logger, peersHome);
        String title = "";
        if (!Utils.DEFAULT_PEERS_HOME.equals(peersHome)) {
            title = peersHome;
        }
        title += "IP电话客户端";
        mainFrame = new JFrame(title);
        mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        mainFrame.addWindowListener(this);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JPanel dialerPanel = new JPanel();

        JLabel jLabel = new JLabel("输入分机号:");

        uri = new JTextField("101", 35);
        uri.addActionListener(this);

        JButton actionButton = new JButton("拨打");
        actionButton.addActionListener(this);

        dialerPanel.add(jLabel);
        dialerPanel.add(uri);
        dialerPanel.add(actionButton);
        dialerPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        statusLabel = new JLabel(title);
        statusLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        Border border = BorderFactory.createEmptyBorder(0, 2, 2, 2);
        statusLabel.setBorder(border);

        mainPanel.add(dialerPanel);
        mainPanel.add(statusLabel);

        Container contentPane = mainFrame.getContentPane();
        contentPane.add(mainPanel);

        JMenuBar menuBar = new JMenuBar();


        registration = new Registration(statusLabel, logger);

        Thread thread = new Thread(() -> {
            String peersHome1 = Utils.DEFAULT_PEERS_HOME;
            if (args.length > 0) {
                peersHome1 = args[0];
            }
            eventManager = new EventManager(MainFrame.this, peersHome1, logger, soundManager);
            eventManager.register();
        }, "gui-event-manager");
        thread.start();

        try {
            while (eventManager == null) {
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
            return;
        }


        JMenu menu = new JMenu("编辑");
        menu.setMnemonic('E');
        JMenuItem menuItem = new JMenuItem("设置账号密码");
        menuItem.setMnemonic('A');
        //添加事件监听器
        menuItem.setActionCommand(EventManager.ACTION_ACCOUNT);
        menuItem.addActionListener(eventManager);
        menu.add(menuItem);
        menuBar.add(menu);


        mainFrame.setJMenuBar(menuBar);

        mainFrame.pack();
        mainFrame.setVisible(true);
    }

    // window events

    @Override
    public void windowActivated(WindowEvent e) {
    }

    @Override
    public void windowClosed(WindowEvent e) {
        eventManager.windowClosed();
    }

    @Override
    public void windowClosing(WindowEvent e) {
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
    }

    @Override
    public void windowIconified(WindowEvent e) {
    }

    @Override
    public void windowOpened(WindowEvent e) {
    }

    // action event

    @Override
    public void actionPerformed(ActionEvent e) {
        //sip:101@123.139.85.225
        String text = uri.getText();
        String uri;
        uri = "sip:" + text + "@" + "1.1.1.1";
        eventManager.callClicked(uri);

    }

    // misc.
    public void setLabelText(String text) {
        statusLabel.setText(text);
        mainFrame.pack();
    }

    public void setLabelText2(String text) {
        String oldText = statusLabel.getText();
        String[] s = oldText.split(" ");
        statusLabel.setText(s[0]+"    "+text);
        mainFrame.pack();
    }

    public void registerFailed() {
        registration.registerFailed();
    }

    public void registerSuccessful() {
        registration.registerSuccessful();
    }

    public void registering() {
        registration.registerSent();
    }


    private String getAddressByUsername(String username) throws IOException, InterruptedException {


        String cookie = getCookie();

        var request = HttpRequest.newBuilder()
                .uri(URI.create("http://124.223.170.227:8080/dbajax/localuser/list"))
                .header("Cookie", cookie)
                .GET()
                .build();
        var client = HttpClient.newHttpClient();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        String body = response.body();
        String begin = "{\"data\":";
        String end = "}";
        String data = begin + body + end;
        JSONObject jsonObject = JSON.parseObject(data);
        JSONArray error = jsonObject.getJSONArray("data");
        List<Account> accounts = JSON.parseObject(error.toJSONString(), new TypeReference<>(){});
        for (Account account : accounts) {
            if (account.getUsrname().equals(username) & !account.getAddr().isBlank()) {
                return account.getAddr();
            }
        }
        return "null";
    }

    private String getCookie() throws IOException, InterruptedException {
        var request = HttpRequest.newBuilder()
                .uri(URI.create("http://124.223.170.227:8080/authorize?password=admin"))
                .GET()
                .build();
        var client = HttpClient.newHttpClient();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        HttpHeaders headers = response.headers();
        Optional<String> cookie = headers.firstValue("set-cookie");
        String s = cookie.get();
        String[] split = s.split(";");
        return split[0];
    }


}
